(function(){
    var _POSTDATATYPEMAP={
        "form" : "application/x-www-form-urlencoded",
        "json" : "application/json"
    };
    function ljAjax(opts){
        this.type         = opts.type || "get";
        this.url          = opts.url;
        this.param        = opts.param || {"date": new Date().getTime()};//请求参数为空默认为当前时间
        this.isShowLoader = opts.isShowLoader === undefined?true:opts.isShowLoader;
        this.dataType     = opts.dataType || "";
        this.onSuccess    = opts.onSuccess;
        this.onError      = opts.onError || this.defaultOnError;
        this.onComplete   = opts.onComplete;
        this.contentType  = opts.contentType || "form";
        this.async        = opts.async === undefined?true:opts.async;
        this.reporter     = opts.reporter || this.defaultReport;
        this.header       = opts.header || "";
        this.init();
    }

    ljAjax.prototype = {
        _loadingId : 0,
        //初始化
        init: function(){
            this.sendRequest();
        },
        //渲染loader
        showLoader: function(request){
            if(this.header!=="")
            {
                var dataformate = Object.prototype.toString.call(this.header);
                if(dataformate==="[object Object]")
                {
                    for(k in header)
                    {
                        request.setRequestHeader(k, this.header[k]);
                    }
                }
                else if(dataformate==="[object Array]")
                {
                    $(this.header).each(function (i,n) {
                        request.setRequestHeader(k, this.header[k]);
                    });
                }
                else if(dataformate==="[object String]")
                {
                    request.setRequestHeader("token", this.header);
                }
            }
            if(this.isShowLoader){
                //使用系统自带的组件显示loading
                var loading = (window.App || window.parent.App);
                if(loading) {
                    loading.blockUI({
                        target: '#tab-content',
                        boxed: true,
                        message: '加载中......'//,
                        // animate: true
                    });
                }
                //使用layer组件 显示loading
/*                if(layer)
                {
                    this._loadingId = layer.load(2,{shade: 0.2});
                }*/
                /*var loader = '<div class="ajaxLoader"><div class="loader">加载中...</div></div>';
                $("body").append(loader);*/
            }
        },
        //隐藏loader
        hideLoader: function(){
            if(this.isShowLoader){
                var loading = (window.App || window.parent.App);
                if(loading) {
                    loading.unblockUI('#tab-content');
                }

                /*$(".ajaxLoader").remove();*/
                /*if(layer)
                {
                    layer.close(this._loadingId);
                }*/
            }
        },
        //发送请求
        sendRequest: function(){
            var self = this;
            var wathcher = new Date();
            var dataformate = Object.prototype.toString.call(this.param);
            if(dataformate==="[object Object]")
            {
                if(this.type=== "get") {
                    this.contentType = "form";
                    var p = [];
                    for(var k in this.param)
                    {
                        p[p.length] = k+"="+this.param[k];
                    }
                    this.param = p.join("&");
                }
                else
                {
                    this.contentType = "json";
                    this.param = JSON.stringify(this.param);
                }
            }
            else if(dataformate==="[object Array]")
            {
                if(this.contentType === "json")
                {
                    this.param = JSON.stringify(this.param);
                }
                else if(this.contentType === "form")
                {
                    this.param = this.param.join("&");
                }
            }
            $.ajax({
                async: this.async,
                type: this.type,
                url: this.url,
                data: this.param,
                dataType:  this.dataType,
                contentType: _POSTDATATYPEMAP[this.contentType],
                beforeSend: function(request){self.showLoader.call(self,request);},
                success: function(res,textStatus,resObj){
                    //检查有没有来自服务端响应头header token
                    var token =resObj.getResponseHeader('token');
                    if(token)
                    {
                        window.sessionStorage.setItem("token",token);
                    }
                    self.hideLoader();
                    self.reporter(true,new Date()-wathcher);
                    if (res != null && res != "") {
                        if(self.onSuccess){
                            if (Object.prototype.toString.call(self.onSuccess) === "[object Function]") {   //Object.prototype.toString.call方法--精确判断对象的类型
                                self.onSuccess(res,textStatus,resObj);
                            }else{
                                console.log("onSuccess is not a function");
                            }
                        }
                    }
                },
                error:function (req, status, msg) {
                    self.hideLoader();
                    if(self.onError){
                        if (Object.prototype.toString.call(self.onError) === "[object Function]") {   //Object.prototype.toString.call方法--精确判断对象的类型
                            self.onError(req,status, msg);
                        }else{
                            console.log("onError is not a function");
                        }
                    }
                },
                complete:function () {
                    if(self.onComplete)
                    {
                        self.onComplete();
                    }
                }
            });
        },
        defaultOnError:function (req, status, msg) {
            var _msg = msg;
            if(this.dataType === "json" && req.responseJSON)
            {
                _msg = "[" + req.status + "]" + req.responseJSON.error;
            }
            else
            {
                _msg = "[" + req.status + "]" + req.responseText;
            }
            if(layer)
            {
                layer.alert(_msg, {
                    icon: 2
                })
            }
            else {
                alert(_msg);
            }
        },
        defaultReport:function (result,spantime) {
            var _repoter = $($("#actionStatusRepoter")[0]||$(window.parent.document).find("#actionStatusRepoter")[0]);
            if(_repoter.length===1)
            {
                _repoter.html("<strong>数据请求"+(result?"成功：":"失败：")+"</strong><span>用时"+spantime+"ms</span>");
            }
        }

    };

    jQuery.ljPost = function (options) {
        options.type = "post";
        options.dataType = "json";
        return new ljAjax(options);
    };
    jQuery.ljGet = function (options) {

        return new ljAjax(options);
    }

})();
